//
//  HJSupportController.m
//  KaiChat
//
//  Created by lx on 2023/12/22.
//

#import "HJSupportController.h"
#import "HJSupportMessageController.h"
#import "HJSupportInputController.h"
#import "HJIM.h"
#import "HJChatMessageLayoutHeader.h"
#import "TUIDefine.h"
#import "HJChatMessageModel.h"
#import "HJAlertController.h"
#import "HJUserInfoController.h"
#import "HJWebViewController.h"

@interface HJSupportController ()<HJSupportInputControllerDelegate, HJSupportMessageControllerDelegate>


@property (nonatomic, assign) BOOL responseKeyboard;
@property (nonatomic, assign) BOOL firstAppear;
@property (nonatomic, assign) BOOL hasClearReadFire;
@property (nonatomic, weak) HJSupportMessageController *messageController;
@property (nonatomic, weak) HJSupportInputController *inputController;
@property (nonatomic, copy) NSString *sessionId;

@end

@implementation HJSupportController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.title = @"Kai support";
    self.view.backgroundColor = UIColor.tj_F6F6F6Color;
    
    IQKeyboardManager.sharedManager.enable = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self addMessageController];
    [self addInputController];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSendMessageCompleteNotification:) name:sendMessageCompleteNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleReceiveNewMessageNotification:) name:receiveNewMessageNotification object:nil];
    
    self.sessionId = getOfficiaSessionId(@(KaiSupportSessionId));
    [HJIM.shareIM.conversationManager readOfficialMessageWithSessionId:self.sessionId];
}

- (void)handleReceiveNewMessageNotification:(NSNotification *)not {
    dispatch_async_main_queue(^{
        HJChatMessageModel *messageModel = not.object;
        if (![self.navigationController.viewControllers containsObject:self]) return;
        if ([messageModel.sessionId isEqualToString:self.sessionModel.sessionId]) {
            [self addNewMessage:messageModel];
        }
    });
}

- (void)handleSendMessageCompleteNotification:(NSNotification *)not {
    HJChatMessageModel *messageModel = not.object;
    [self updateMessage:messageModel];
}


- (void)addMessageController {
    
    HJSupportMessageController *messageController = [[HJSupportMessageController alloc] init];
    messageController.delegate = self;
    messageController.sessionModel = self.sessionModel;
    [self addChildViewController:messageController];
    [self.view addSubview:messageController.view];
    [messageController didMoveToParentViewController:self];
    messageController.view.frame = CGRectMake(0, KNavBarHight,
                                              self.view.frame.size.width,
                                              self.view.frame.size.height - TTextView_Height - TabbarSafeBottomMargin - KNavBarHight);
    
    _messageController = messageController;
}

- (void)addInputController {
    HJSupportInputController *inputController = [[HJSupportInputController alloc] init];
    inputController.delegate = self;
    [self addChildViewController:inputController];
    [self.view addSubview:inputController.view];
    inputController.view.frame = CGRectMake(0, self.view.frame.size.height - (TTextView_Height + TabbarSafeBottomMargin),
                                            self.view.frame.size.width,
                                            TTextView_Height + TabbarSafeBottomMargin);
    _inputController = inputController;
}

- (void)didTapInMessageController:(HJSupportMessageController *)controller {
    [self.inputController reset];
}

- (void)messageControllerNeedResetInput:(HJSupportMessageController *)controller {
    [self.inputController reset];
}

- (void)messageController:(HJSupportMessageController *)controller onSelectMessageAvatar:(HJChatMessageCell *)cell {
    HJChatMessageModel *messageModel = cell.messageLayout.messageModel;
    if (messageModel.senderId.integerValue == KaiSupportSessionId) return;
    HJUserInfoController *userInfoController = [[HJUserInfoController alloc] init];
    userInfoController.userId = messageModel.senderId;
    [self.navigationController pushViewController:userInfoController];
}

- (void)messageController:(HJSupportMessageController *)controller onLongSelectMessageAvatar:(HJChatMessageCell *)cell {
    
    
}


- (void)messageController:(HJSupportMessageController *)controller didClickRetryButton:(HJChatMessageCell *)cell {
    HJChatMessageLayout *messageLayout = cell.messageLayout;
    HJChatMessageModel *messageModel = messageLayout.messageModel;
    [self sendMessageWithModel:messageModel];
}

- (void)messageController:(HJSupportMessageController *)controller onSelectMessageContent:(HJChatMessageCell *)cell {
    
    [self.inputController reset];
    
    HJChatMessageLayout *messageLayout = cell.messageLayout;
    NSDictionary *data = messageLayout.messageModel.msg.mj_JSONObject;
    if (!isEmptyString(data[@"url"])) {
        HJWebViewController *webViewController = [[HJWebViewController alloc] init];
        webViewController.title = data[@"title"];
        webViewController.url = [NSString stringWithFormat:@"%@?article_id=%@", data[@"url"], data[@"id"]];
        [self presentViewController:webViewController animated:YES completion:nil];
    }
}


- (void)inputController:(HJSupportInputController *)inputController didChangeHeight:(CGFloat)height {
    
    if (!self.responseKeyboard) {
        return;
    }
    
    UIViewAnimationOptions animationOptions = 7 << 16;
    [UIView animateWithDuration:0.25 delay:0 options:animationOptions animations:^{
        CGRect msgFrame = self.messageController.view.frame;
        msgFrame.size.height = self.view.frame.size.height - KNavBarHight - height;
        self.messageController.view.frame = msgFrame;
        
        CGRect inputFrame = self.inputController.view.frame;
        inputFrame.origin.y = msgFrame.origin.y + msgFrame.size.height;
        inputFrame.size.height = height;
        self.inputController.view.frame = inputFrame;
        
        [self.messageController scrollToBottom:NO];
        
    } completion:nil];
    
}

- (void)inputController:(HJSupportInputController *)inputController didSendTextMessage:(NSString *)text {
    [self sendTextMessageByText:text];
}

- (void)inputControllerDidClickFAQ:(HJSupportInputController *)inputController {
    [HJIM.shareIM.chatManager getFAQMessageCompletion:^(HJChatMessageModel * _Nullable replyMessageModel, NSError * _Nullable error) {
        
    }];
}

- (void)sendTextMessageByText:(NSString *)text {
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.sessionId = self.sessionModel.sessionId;
    messageModel.content = text;
    messageModel.sessionName = self.sessionModel.sessionName;
    messageModel.sessionAvatar = self.sessionModel.sessionAvatar;
    [self sendMessageWithModel:messageModel];
}

- (void)sendMessageWithModel:(HJChatMessageModel *)messageModel {
    [[HJIM shareIM].chatManager sendKeywordReplyMessageWithModel:messageModel begin:^{
        [self addNewMessage:messageModel];
    } completion:^(HJChatMessageModel * _Nullable replyMessageModel, NSError * _Nullable error) {
    }];
}


- (void)didReceiveNewMessage:(HJChatMessageModel *)messageModel {
    HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
    [HJIM.shareIM.conversationManager readMessageWithSessionId:messageModel.sessionId msgIds:@[messageModel.serverMsgId] completion:nil];
    [self.messageController addNewMessage:messageLayout];
}

- (void)addNewMessage:(HJChatMessageModel *)messageModel {
    
    if (messageModel.isRetry) {
        HJChatMessageLayout *messageLayout = nil;
        for (HJChatMessageLayout *layout in [self.messageController.messageLayouts reverseObjectEnumerator]) {
            if ([layout.messageModel.msgId isEqualToString:messageModel.msgId]) {
                messageLayout = layout;
                break;
            }
        }
        
        if (messageLayout) {
            [self.messageController.messageLayouts removeObject:messageLayout];
        }
        
        dispatch_async_sql_queue(^{
            [HJIM.shareIM.messageManager deleteMessageWithMessageModel:messageModel];
        });
    }
    
    HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
    [self.messageController addNewMessage:messageLayout];
}

- (void)updateMessage:(HJChatMessageModel *)messageModel {
    [self.messageController updateMessage:messageModel];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    IQKeyboardManager.sharedManager.enable = NO;
    
    self.responseKeyboard = YES;
    if (self.firstAppear) {
        self.firstAppear = NO;
    }
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    IQKeyboardManager.sharedManager.enable = YES;
    self.responseKeyboard = NO;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    TJLog(@"%s", __func__);
}



@end
